package com.flying.flow.util;

import java.util.Map;

import com.flying.common.util.JSONUtils;
import com.flying.common.util.ServiceHelper;
import com.flying.common.util.StringUtils;
import com.flying.framework.data.Data;

public abstract class FlowUtils {
	public static boolean checkExpectTime(String expectTime) {
		try {
			parseExpectTimeAsSeconds(expectTime);
			return true;
		} catch(Exception e) {
			return false;
		}
	}
	public static int parseExpectTimeAsSeconds(String expectTime) {
		if(StringUtils.isEmpty(expectTime)) return 0;
		expectTime = expectTime.toLowerCase();
		int day = 0;
		int di = expectTime.indexOf("d");
		if(di >0) {
			day = Integer.parseInt(expectTime.substring(0, di).trim());
			expectTime = expectTime.substring(di + 1);
		}
		int hour = 0;
		int hi = expectTime.indexOf("h");
		if(hi >0) {
			hour = Integer.parseInt(expectTime.substring(0, hi).trim());
			expectTime = expectTime.substring(hi + 1);
		}
		int min = 0;
		int mi = expectTime.indexOf("m");
		if(mi >0) {
			min = Integer.parseInt(expectTime.substring(0, mi).trim());
			expectTime = expectTime.substring(mi + 1);
		}
		int sec = 0;
		int si = expectTime.indexOf("s");
		if(si >0) {
			sec = Integer.parseInt(expectTime.substring(0, si).trim());
		}
		return day * 24 * 3600+hour * 3600 + min * 60 + sec;
	}
	
	public static Data process(String form_action, Data data) throws Exception {
		if(form_action == null) return null;
		String[] actions = StringUtils.split(form_action, ":");
		if(data == null) data = new Data();
		return ServiceHelper.invoke(actions[0], actions[1]+":"+actions[2], data);
	}
	
	public static Data process(String form_action, String json, Map<String, Object> env) throws Exception {
		if(form_action == null) return null;
		String[] actions = StringUtils.split(form_action, ":");
		Data data = parse(json);
		if(env != null) {
			data.putAll(env);
		}
		return ServiceHelper.invoke(actions[0], actions[1]+":"+actions[2], data);
	}
	
	public static Data parse(String json) {
		return new Data(JSONUtils.toMap(json));
	}
	
	public static void main(String[] args) {
		System.out.println(parseExpectTimeAsSeconds("0d 0h 10m"));
	}
}
